<template>
    <div class="list1 institution">
        <div class="foldbar" :class="{'fold':!foldSwitch}" @click="switchFold"><i></i>点击{{foldInf=foldSwitch?'收起':'展开'}}</div>
        <div class="search" v-if="foldSwitch">
            <div>
                <div class="c-item">
                    <p class="title">单位名称</p>
                    <p class="name" @click="companyPropShow = true"><input class="bn" readonly v-model="DeptName" type="text" style="padding-right:20px;"><x-icon type="ios-arrow-right" size="20" style="fill:#c8c8cd;"></x-icon></p>
                </div>
                <div>
                    <div class="form-item form-item-style1 form-item-time">
                        <div class="label-title">
                            <label>访问开始时间</label>
                        </div>
                        <group>
                            <datetime placeholder="请选择日期" v-model="startTime" format="YYYY-MM-DD" @on-change="changeStartTime"></datetime>
                        </group>
                    </div> 
                </div>
                <div>
                    <div class="form-item form-item-style1 form-item-time">
                        <div class="label-title">
                            <label>访问结束时间</label>
                        </div>
                        <group>
                            <datetime placeholder="请选择日期" v-model="endTime" format="YYYY-MM-DD" @on-change="changeEndTime"></datetime>
                        </group>
                    </div> 
                </div>
                <div class="c-item">
                    <p class="title">访客姓名/事由</p>
                    <div class="name">
                        <input  class="bn" type="text" v-model="name" placeholder="点击输入">  
                    </div>
                </div>
                <div class="btns">
                    <div class="submit" @click="onSearch">查询</div>
                </div>
            </div>
        </div>
        <div class="bscroll-wrap">
            <div ref="bscrollEl" class="bscroll" :class="{'fold-scroll':!foldSwitch}">
                <vue-better-scroll class="wrapper"
                                ref="scroll0"
                                :scrollbar="scrollbarObj"
                                :pullDownRefresh="pullDownRefreshObj"
                                :pullUpLoad="pullUpLoadObj"
                                :startY="parseInt(startY)"
                                @pullingDown="onPullingDown"
                                @pullingUp="onPullingUp">
                    <div ref="bscrollContainer" class="bscroll-container">
                        <!-- 内容部分 -->
                        <div class="list1_main">
                            <noData v-if="!listArr.length"></noData>
                            <ul class="list1Box">
                                <li v-for="(item,index) in listArr"
                                    :key="index"
                                    @click="goPreview(item)">
                                    <h6>访客姓名：{{item.UserName}}
                                        <span class="listtime"
                                            size="20">{{item.AccessTime}}</span>
                                    </h6>
                                    <p>访问事由：{{item.Cause}}</p>
                                </li>
                            </ul>
                        </div>
                    </div>
                </vue-better-scroll>
            </div>
        </div>
        <addMenu v-if="isGlry" @add="add"></addMenu>
        <myMenu></myMenu>
        <companyProp :companyPropShow="companyPropShow"
                :selectCompany="selectCompanyTeam"></companyProp>
        <!-- <div class="bs-workmain-add" @click="addVisitor"></div> -->
    </div>
</template>
<script>
import { XSwitch, Group, Cell, Previewer, TransferDom } from 'vux'
import VueBetterScroll from 'vue2-better-scroll'
import http from '../../../axios/public'
import myMenu from '@/commonComponents/menu'
import addMenu from '@/commonComponents/addmenu'
import companyProp from '@/commonComponents/companyProp'
export default {
    components: {
        VueBetterScroll,
        myMenu,
        addMenu,
        companyProp
    },
    data () {
        return {
            userInfo: {},
            isGlry: true, // 是否是管理员
            name: '', // 查询关键词
            listArr: [], // 列表数据
            // dropDown: false
            // 这个配置可以开启滚动条，默认为 false。当设置为 true 或者是一个 Object 的时候，都会开启滚动条，默认是会 fade 的
            scrollbarObj: {
                fade: true
            },
            // 这个配置用于做下拉刷新功能，默认为 false。当设置为 true 或者是一个 Object 的时候，可以开启下拉刷新，可以配置顶部下拉的距离（threshold） 来决定刷新时机以及回弹停留的距离（stop）
            pullDownRefreshObj: {
                threshold: 50,
                stop: 40
            },
            // 这个配置用于做上拉加载功能，默认为 false。当设置为 true 或者是一个 Object 的时候，可以开启上拉加载，可以配置离底部距离阈值（threshold）来决定开始加载的时机
            pullUpLoadObj: {
                threshold: 0,
                txt: {
                    more: '加载更多',
                    noMore: '没有更多数据了'
                }
            },
            startY: 0, // 纵轴方向初始化位置
            listCount: 0, // 当前列表条数
            listAllCount: 0, // 总条数
            pageIndex: 1,
            addPath: '/visitor',
            deptid: '',//单位id
            DeptName: '',
            companyPropShow: false,
            startTime: '',
            endTime: '',
            foldSwitch: true
        }
    },
    created () {
        // 获取用户信息，判断是否有操作权限
        this.userInfo = JSON.parse(localStorage.getItem('registerInfo')) || {}
        this.deptid = this.userInfo.departId
        this.DeptName = this.unescape(this.userInfo.departName)
        this.$axiosAjax.GetIsManager({
            userNo: this.userInfo.userId
        }).then(res => {
            if (res.data.code == 1) {
                this.isGlry = true
            } else {
                this.isGlry = false
            }
        })
    },
    mounted () {
        this.onPullingDown()
    },
    methods: {
        // 初始化获取数据
        getData () {
            this.$vux.loading.show({
                text: '加载中...'
            })
            let formData = new FormData()
            let params = {
                pageSize: 10,
                pageIndex: this.pageIndex,
                name: this.name,
                deptid: this.deptid,
                startTime: this.startTime,
                endTime: this.endTime,
            }
            formData.append('json', JSON.stringify(params))
            return http.fetchPost('/api/Fktz/GetList', formData)
        },
        delItem(id) {
            let params2 = {
                id: id
            }
            http.fetchGet('/api/Fktz/Delete',params2)
            .then(res =>{
                if(res.data.code === 0){
                    this.$vux.toast.text('记录删除成功')
                    this.onPullingDown()
                }else{
                    this.$vux.toast.text(res.data.info)
                }
            })
        },
        onPullingDown () {
            // 模拟下拉刷新
            this.listCount = 0
            this.pageIndex = 1
            let that = this
            this.getData().then(res => {
                if (res.data.Code == 0) {
                    that.listArr = res.data.Data
                    that.formatTime(that.listArr)
                    that.listCount = that.listArr.length
                    that.listAllCount = res.data.Count
                    that.$vux.loading.hide()
                }
                if (that.listCount < that.listAllCount) {
                    that.$refs.scroll0.forceUpdate(true)
                } else {
                    that.$refs.scroll0.forceUpdate(false)
                }
            }).finally(() => {
                that.$vux.loading.hide()
            })
        },
        onPullingUp () {
            let that = this
            this.pageIndex++
            // 模拟上拉 加载更多数据
            this.getData().then(res => {
                if (res.data.Code === 0) {
                    that.listArr = that.listArr.concat(res.data.Data)
                    that.formatTime(that.listArr)
                    that.listCount = that.listArr.length
                    that.listAllCount = res.data.Count
                    that.$vux.loading.hide()
                }
                if (that.listCount < that.listAllCount) {
                    that.$refs.scroll0.forceUpdate(true)
                } else {
                    that.$refs.scroll0.forceUpdate(false)
                }
            }).finally(() => {
                that.$vux.loading.hide()
            })
        },
        selectCompanyTeam (item) {
            console.log(item)
            this.DeptName = this.unescape(item.UnitName)
            this.deptid = item.UnitId
            this.companyPropShow = false
            this.onPullingDown()
        },
        //时间格式化
        formatTime(arr){
            var that = this
            if(arr.length>0){
                arr.forEach(item => {
                    if(item.AccessTime&&item.AccessTime.length>0){
                        that.$set(item,'AccessTime',item.AccessTime.substr(0,16))
                    }
                });
            }
        },
        //特殊字符转化
        unescape(html) {
            return html
                .replace(html ? /&(?!#?\w+;)/g : /&/g, '&amp;')
                .replace(/&lt;/g, '<')
                .replace(/&gt;/g, '>')
                .replace(/&quot;/g, '"')
                .replace(/%23/g, '#')
        },
        // 获取当前日期、时间
        getdatenew () {
            var date = new Date()
            var seperator1 = '-'
            var year = date.getFullYear()
            var month = date.getMonth() + 1
            var strDate = date.getDate()
            var hour = date.getHours()
            var minute = date.getMinutes()
            if (month >= 1 && month <= 9) {
                month = '0' + month
            }
            if (strDate >= 0 && strDate <= 9) {
                strDate = '0' + strDate
            }
            if (hour >= 0 && hour <= 9) {
                hour = '0' + hour
            }
            if (minute >= 0 && minute <= 9) {
                minute = '0' + minute
            }
            var currentdate = year + seperator1 + month + seperator1 + strDate + ' ' + hour + ':' + minute
            return currentdate
        },
         // 切换开始时间
        changeStartTime (val) {
            if (this.checkTime(val, this.endTime)) {
                // this.onPullingDown()
            }
        },
        // 切换结束时间
        changeEndTime (val) {
            if (this.checkTime(this.startTime, val)) {
                // this.onPullingDown()
            }
        },  
         // 验证开始和结束时间
        checkTime (startTime, endTime) {
            if (startTime.length > 0 && endTime.length > 0) {
                var startTmp = startTime.split('-')
                var endTmp = endTime.split('-')
                var sd = new Date(startTmp[0], startTmp[1], startTmp[2])
                var ed = new Date(endTmp[0], endTmp[1], endTmp[2])
                if (sd.getTime() > ed.getTime()) {
                    this.$vux.toast.text('开始日期不能大于结束日期')
                    return false
                }
            }
            return true         
        },
        // 搜索
        onSearch (item) {
            this.pageIndex = 1
            this.onPullingDown()
        },
        addVisitor () {
            this.$router.push({
                path: '/visitor'
            })
        },
        goPreview (item) {
            this.$router.push({
                path: '/visitorDetail',
                query: {
                    FktzId: item.FktzId
                }
            })
        },
        //新增
        add () {
            this.$router.push('/visitor')
            // wx.miniProgram.redirectTo({
            //     url: `/pages/share/index?type=${this.$route.query.type}`
            // })
        },
        switchFold() {
            this.foldSwitch = !this.foldSwitch
            let containerHeight = parseFloat(getComputedStyle(this.$refs.bscrollEl, null).getPropertyValue('min-height'))
            // console.log(containerHeight,this.$refs.bscrollContainer.offsetHeight);
            if(this.$refs.bscrollContainer.offsetHeight<containerHeight){
                this.$refs.bscrollEl.style.height = this.$refs.bscrollContainer.offsetHeight + 'px'
            }
        },
    }
}
</script>
<style lang="less" scoped>
.list1 {
    width: 100%;
    height: 100%;
    font-size: 14px;
    background: #ebeef2;
    position: relative;
    .list1_main {
        // height: 627px;
        padding-bottom: 50px;
        width: 100%;
        .no-data {
            background-color: #fff;
        }
        .searchDiv {
            background-color: #fff;
            padding: 10px 0;
            position: relative;
            .searchbtn {
                width: 24px;
                height: 25px;
                position: absolute;
                top: 18px;
                right: 30px;
                background: url('../../../../static/images/s_03.png') no-repeat
                    center;
                background-size: 24px 25px;
            }
            .search {
                width: 335px;
                margin: 0 auto;
                height: 40px;
                line-height: 40px;
                padding-left: 10px;
                box-sizing: border-box;
                border-radius: 10px;
                display: block;
                border: 1px solid #999;
            }
        }
    }
    .list1Box {
        width: 100%;
        background-color: #fff;
        padding-left: 30px;
        .fileTit {
            font-size: 14px;
            font-weight: normal;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            margin-right: 50px;
        }
        li {
            // height: 82px;
            border-bottom: 1px solid #f0eff4;
            padding: 18px 20px 14px 0;
            position: relative;
            h6 {
                line-height: 28px;
                font-size: 14px;
                font-weight: bold;
                color: #333;
            }
            p {
                line-height: 24px;
                color: #666;
            }
            .listtime {
                float: right;
                color: #999;
            }
            .vux-x-icon {
                fill: #999;
                float: right;
                width: 20px;
                height: 20px;
            }
        }
    }
    .bs-workmain-add {
        width: 75px;
        height: 75px;
        position: fixed;
        right: 50px;
        bottom: 50px;
        background: url('../../../../static/images/add2.png') no-repeat left top;
    }
}
.bscroll {
    position: absolute;
    top: 253px;
    bottom: 0;
    left: 0px;
    right: 0;
    overflow: hidden;
    min-height: 584px!important;
    // margin-top: 253px;
}
.bscroll.fold-scroll{
    top: 20px;
}
.bscroll-container li {
    border-bottom: 1px solid #efeff4;
    padding: 18px 20px 12px 0;
    height: 90px;
}
.foldbar{
    width: 100%;
    height: 20px;
    line-height: 20px;
    display: flex;
    display: -webkit-flex;
    justify-content: center;
    text-align: center;
    background: #ebeef2;
    position: absolute;
    top: 233px;
    color: #aaa;
    font-size: 14px;
    z-index: 4;
    i{  
        display: inline-block;
        width: 28px;
        height: 20px;
        background: url('../../../assets/icon_fold.png') center center no-repeat;
    }
}
.foldbar.fold{
    top: 0;
    i{  
        background: url('../../../assets/icon_unfold.png') center center no-repeat;
    }
    
}
// 搜索区域
.search {
    width: 100%;
    padding: 10px 20px 20px;
    position: relative;
    background-color: #fff;
    margin-bottom: 20px;
    .form-item-time{
        height: 40px;
        line-height: 40px;
        margin-left: 0;
        padding-right: 0;
    }
    input {
        width: 100%;
        height: 36px;
        border: 1px solid #eee;
        border-radius: 8px;
        padding-left: 10px;
        &.bn {
            border: none;
        }
    }
    button {
        width: 48px;
        height: 28px;
        background: url('../../../assets/search.png') no-repeat center;
        background-size: 28px 28px;
        position: absolute;
        top: 14px;
        right: 30px;
    }
    .btns {
            width: 100%;
            display: flex;
            justify-content: center;
            background-color: #fff;
            .save, .submit {
                width: 150px;
                height: 30px;
                line-height: 30px;
                border-radius: 15px;
                text-align: center;
                color: #fff;
                background-color: #2269FC;
            }
            padding-top: 10px;
            padding-bottom: 0;
        }
    .c-item {
        height: 40px;
        line-height: 40px;
        // padding: 0 20px;
        display: flex;
        justify-content: space-between;
        border-bottom: 1px solid #f3f3f3;
        background-color: #fff;
        &.auto {
            height: auto;
            position: relative;
            width: 100%;
            .name {
                right: 0;
            }
        }
        .name {
            text-align: right;
            color: #999;
            position: relative;
            svg {
                position: absolute;
                // right: 15px;
                right: -5px;
                top: 50%;
                transform: translateY(-50%);
            }
            &.auto {
                max-width: 180px;
                height: auto;
                line-height: normal;
                padding: 5px 0;
                float: right;
                textarea {
                    border: none;
                    text-align: right;
                    font-size: 14px;
                }
            }
            .inline-x-switch {
                top: 9px
            }
            .weui-switch:checked {
                border-color: #2269FC;
                background-color: #2269FC
            }
            input {
                text-align: right;
                color: #999;
                font-size: 14px!important;
                &::-webkit-input-placeholder { /* WebKit browsers */
                    direction: rtl;
                    font-size: 14px;
                }
                &::-moz-placeholder { /* Mozilla Firefox 4 to 18 */
                    direction: rtl;
                    font-size: 14px;
                }
                &::-moz-placeholder { /* Mozilla Firefox 19+ but I'm not sure about working */
                    direction: rtl;
                    font-size: 14px;
                }
                &::-ms-input-placeholder { /* Internet Explorer 10+ */
                    direction: rtl;
                    font-size: 14px;
                }
            }
        }
        .title {
            .red {
                color: red;
            }
        }
    }
    
}
</style>
